package cn.imvc.app.models;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

import cn.imvc.app.entities.VoucherTemplate;
import cn.imvc.app.repositories.VoucherTemplateRepository;
import cn.imvc.data.domain.ViewRequest;

@Service
public class VoucherTemplateModelImpl implements VoucherTemplateModel{
	@Autowired
	private VoucherTemplateRepository voucherTemplateRepository;
	@Autowired
	private UserModel userModel;
	@Autowired
	private RefRelationModel refRelationModel;

	@Override
	public Page<VoucherTemplate> findAll(ViewRequest viewRequest) {
		if(viewRequest == null){
			viewRequest = new ViewRequest();
		}
		return voucherTemplateRepository.findAll(viewRequest);
	}

	@Override
	public void save(VoucherTemplate voucherTemplate) {
		voucherTemplate.setUserId(userModel.getSessionUser().getId());
		voucherTemplateRepository.save(voucherTemplate);
	}

	@Override
	public void update(VoucherTemplate voucherTemplate) {
		VoucherTemplate oldV = voucherTemplateRepository.findOne(voucherTemplate.getId());
		BeanUtils.copyProperties(voucherTemplate, oldV,new String[]{"id"});
		voucherTemplateRepository.saveAndFlush(oldV);
	}

	@Override
	public String delete(int id) {
		String result = refRelationModel.deleteDateCheck("voucher_template", "id", id);
		
		if(result.equals("")){
			voucherTemplateRepository.delete(id);
			return "";
		}else{
			return result;
		}
	}

	@Override
	public VoucherTemplate getOne(int id) {
		return voucherTemplateRepository.getOne(id);
	}


}
